package cn.iocoder.yudao.module.system.controller.admin.examclass;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.system.controller.admin.examclass.vo.*;
import cn.iocoder.yudao.module.system.convert.examclass.ExamClassStudentConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.examclass.ExamClassStudentDO;
import cn.iocoder.yudao.module.system.service.examclass.ExamClassStudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 班级学生管理")
@RestController
@RequestMapping("/system/exam-class-student")
@Validated
public class ExamClassStudentController {

    @Resource
    private ExamClassStudentService examClassStudentService;

    @PostMapping("/create")
    @Operation(summary = "创建班级学生关联")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:create')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> createExamClassStudent(@Valid @RequestBody ExamClassStudentCreateReqVO createReqVO) {
        return success(examClassStudentService.createExamClassStudent(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新班级学生关联")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateExamClassStudent(@Valid @RequestBody ExamClassStudentUpdateReqVO updateReqVO) {
        examClassStudentService.updateExamClassStudent(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除班级学生关联")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:delete')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deleteExamClassStudent(@RequestParam("id") Long id) {
        examClassStudentService.deleteExamClassStudent(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得班级学生关联")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:query')")
    public CommonResult<ExamClassStudentRespVO> getExamClassStudent(@RequestParam("id") Long id) {
        ExamClassStudentDO examClassStudent = examClassStudentService.getExamClassStudent(id);
        return success(ExamClassStudentConvert.INSTANCE.convert(examClassStudent));
    }

    @GetMapping("/list")
    @Operation(summary = "获得班级学生关联列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:query')")
    public CommonResult<List<ExamClassStudentRespVO>> getExamClassStudentList(@RequestParam("ids") Collection<Long> ids) {
        List<ExamClassStudentDO> list = examClassStudentService.getExamClassStudentList(ids);
        return success(ExamClassStudentConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得班级学生关联分页")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:query')")
    public CommonResult<PageResult<ExamClassStudentRespVO>> getExamClassStudentPage(@Valid ExamClassStudentPageReqVO pageVO) {
        PageResult<ExamClassStudentDO> pageResult = examClassStudentService.getExamClassStudentPage(pageVO);
        return success(ExamClassStudentConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出班级学生关联 Excel")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportExamClassStudentExcel(@Valid ExamClassStudentPageReqVO exportReqVO,
                                            HttpServletResponse response) throws IOException {
        List<ExamClassStudentDO> list = examClassStudentService.getExamClassStudentList(exportReqVO);
        // 导出 Excel
        List<ExamClassStudentRespVO> datas = ExamClassStudentConvert.INSTANCE.convertList(list);
        ExcelUtils.write(response, "班级学生关联.xls", "数据", ExamClassStudentRespVO.class, datas);
    }

    @GetMapping("/list-by-class")
    @Operation(summary = "根据班级ID获取学生列表")
    @Parameter(name = "classId", description = "班级ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:query')")
    public CommonResult<List<ExamClassStudentRespVO>> getStudentListByClassId(@RequestParam("classId") Long classId) {
        List<ExamClassStudentDO> list = examClassStudentService.getStudentListByClassId(classId);
        return success(ExamClassStudentConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-by-student")
    @Operation(summary = "根据学生ID获取班级列表")
    @Parameter(name = "studentId", description = "学生ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:query')")
    public CommonResult<List<ExamClassStudentRespVO>> getClassListByStudentId(@RequestParam("studentId") Long studentId) {
        List<ExamClassStudentDO> list = examClassStudentService.getClassListByStudentId(studentId);
        return success(ExamClassStudentConvert.INSTANCE.convertList(list));
    }

    @PostMapping("/batch-add")
    @Operation(summary = "批量添加学生到班级")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:create')")
    public CommonResult<Boolean> batchAddStudentsToClass(@RequestParam("classId") Long classId,
                                                         @RequestParam("studentIds") List<Long> studentIds) {
        examClassStudentService.batchAddStudentsToClass(classId, studentIds);
        return success(true);
    }

    @DeleteMapping("/remove")
    @Operation(summary = "从班级中移除学生")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:delete')")
    public CommonResult<Boolean> removeStudentFromClass(@RequestParam("classId") Long classId,
                                                        @RequestParam("studentId") Long studentId) {
        examClassStudentService.removeStudentFromClass(classId, studentId);
        return success(true);
    }

    @DeleteMapping("/batch-remove")
    @Operation(summary = "批量从班级中移除学生")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:delete')")
    public CommonResult<Boolean> batchRemoveStudentsFromClass(@RequestParam("classId") Long classId,
                                                              @RequestParam("studentIds") List<Long> studentIds) {
        examClassStudentService.batchRemoveStudentsFromClass(classId, studentIds);
        return success(true);
    }

    @GetMapping("/export-student-accounts")
    @Operation(summary = "导出某个班级的学生账号信息 Excel")
    @Parameter(name = "classId", description = "班级ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportStudentAccountsExcel(@RequestParam("classId") Long classId,
                                           HttpServletResponse response) throws IOException {
        List<StudentAccountExportExcelVO> list = examClassStudentService.getStudentAccountsForExport(classId);
        
        // 生成包含班级信息的文件名
        String fileName = "学生账号信息.xls";
        if (!list.isEmpty()) {
            StudentAccountExportExcelVO firstStudent = list.get(0);
            String className = firstStudent.getClassName();
            String grade = firstStudent.getGrade();
            fileName = String.format("%s-%s-学生账号信息.xls", grade, className);
        }
        
        // 导出 Excel
        ExcelUtils.write(response, fileName, "数据", StudentAccountExportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入学生到班级")
    @PreAuthorize("@ss.hasPermission('system:exam-class-student:import')")
    @ApiAccessLog(operateType = IMPORT)
    public CommonResult<ExamClassStudentImportRespVO> importStudents(@RequestParam("classId") Long classId,
                                                                     @RequestParam("file") MultipartFile file) throws IOException {
        ExamClassStudentImportRespVO respVO = examClassStudentService.importStudents(classId, file);
        return success(respVO);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得学生导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手工创建导出 demo
        List<ExamClassStudentImportExcelVO> list = examClassStudentService.getImportTemplate();
        // 输出
        ExcelUtils.write(response, "学生导入模板.xls", "学生列表", ExamClassStudentImportExcelVO.class, list);
    }

}